/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.oai.metadataRepository;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

/**
 *
 * @author Martin Rehanek, Martin.Rehanek@gmail.com
 */
public class Tools {

    /**
     * Transforms id in form oai:mzk.cz:oai:aleph.mzk.cz:MZK03-000906761 into
     * oai%3Amzk.cz%3Aoai%3Aaleph.mzk.cz%3AMZK03-000906761
     * @param id
     * @return
     */
    public static String idToFileName(String id) {
        StringBuilder builder = new StringBuilder(id.length());
        for (int i = 0; i < id.length(); i++) {
            char character = id.charAt(i);
            if (character == ':') {
                builder.append("%3A");
            } else {
                builder.append(character);
            }
        }
        builder.append(".xml");
        return builder.toString();
    }

    public static String filenameToId(String filename) {
        //implementation detail: Sun recommends to use String.split instead of StringTokenizer
        //in some situations StringTokenizer can be faster though
        String encodedSeparator = "%3A";
        String[] tokens = filename.split(encodedSeparator);
        StringBuilder builder = new StringBuilder();
        int i;
        for (i = 0; i < (tokens.length - 1); i++) { //last token contains ".xml"
            builder.append(tokens[i]);
            builder.append(':');
        }
        String[] lastTokens = tokens[i].split("\\.");
        builder.append(lastTokens[0]);
        return builder.toString();
    }

    /**
     * Download file from URL and saves as fileName
     * @param URL
     * @param fileName absolute name of the tei5File, where the record should be stored
     * @param fileName absolute name of the log file
     * @throws IOException if i/o error occures while invoking wget
     * @deprecated 
     */
    public void downloadTei5Record(String URL, String fileName, String logFileName) throws IOException {
        int timeout = 3;
        int tries = 3;
        System.out.println("===========wget==============");
        //logFileName = "/tmp/wget.log";
        String command = "wget" + " --timeout=" + timeout + " --tries=" + tries + " --append-output=" + logFileName + " --output-document=" + fileName + " " + URL;
        System.out.println("command: " + command);
        Runtime.getRuntime().exec(command);
        //System.out.println("Downloading '" + URL + "' into file '" + fileName + "'");
        System.out.println("========end of wget===========");
        //TODO: poresit mazani logu, aby nerostly do nekonecna
    }

    public static String errorstreamToString(Process process) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        StringBuilder builder = new StringBuilder();
        String line;
        int lines = 0;
        while ((line = in.readLine()) != null) {
            builder.append(line);
            lines++;
        }
        return builder.toString();
    }

    public static String loadMarcExample() {
        File xml = new File("/home/martin/tmp/marc-test.xml");
        SAXReader reader = new SAXReader();
        Document doc = null;
        try {
            doc = reader.read(xml);
        } catch (DocumentException ex) {
            Logger.getLogger(Tools.class.getName()).log(Level.SEVERE, null, ex);
        }
        return doc.getRootElement().asXML();
    }

}
